package luanvan.app.foodnote;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;

import luanvan.app.foodnote.animation.ActivitySwitcher;
import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.ConnectionDetector;
import luanvan.app.foodnote.library.SessionManager;
import luanvan.app.foodnote.library.UserFunctions;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends SherlockActivity {
	// Session Manager class
	SessionManager session;
	
	UserFunctions userFunction;
	// Progress Dialog
	private ProgressDialog pDialog;
	// Alert Dialog Manager
	AlertDialogManager alertDialogManager = new AlertDialogManager();
	// Connection detector class
    ConnectionDetector cd;
	
	EditText inputUsername;
	EditText inputEmail;
	EditText inputPassword;
	Button btnRegister;
	Button btnRegisterEmail;
	TextView registerErrorMsg;
	
	// JSON
	private static String KEY_SUCCESS = "success";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);

		getSupportActionBar().setIcon(R.drawable.add_user);
		getSupportActionBar().show();
		
		//session = new SessionManager(getApplicationContext());
		userFunction = new UserFunctions();
		
		inputUsername = (EditText) findViewById(R.id.registerName);
		inputEmail = (EditText) findViewById(R.id.registerEmail);
		inputPassword = (EditText) findViewById(R.id.registerPassword);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		
		btnRegister.setOnClickListener(onClickListener);
		
		
	}
	private boolean checkInternet(){
    	boolean isInternetPresent;
    	cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        return isInternetPresent;
    }
    @Override
  	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  		super.onActivityResult(requestCode, resultCode, data);
  		checkInternet();
    }
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnRegister:
				String name = inputUsername.getText().toString();
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString(); 
				if(checkInternet()){
					if(name.trim().length() > 0 && email.trim().length() > 0
							&& password.trim().length() > 0){
						if(isEmailValid(email)){
							new RegisterUser().execute(name, email, password);
						}else {
							alertDialogManager.showAlertDialog(RegisterActivity.this, 
									"Đăng kí", "Email sai định dạng, vui lòng nhập lại!", false);
						}
					}else {
						alertDialogManager.showAlertDialog(RegisterActivity.this, "Đăng kí", 
								"Vui lòng hoàn thành các thông tin cần đăng kí!", false);
					}
				} else {
					showAlertDialog();
				}
				
				break;
			
			}
		}	
	};

	private void animatedStartActivity() {
		// we only animateOut this activity here.
		// The new activity will animateIn from its onResume() - be sure to implement it.
		final Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
		// disable default animation for new intent
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		ActivitySwitcher.animationOut(findViewById(R.id.container), getWindowManager(), 
				new ActivitySwitcher.AnimationFinishedListener() {
			@Override
			public void onAnimationFinished() {
				startActivity(intent);
				finish();
			}
		});
	}
	
	/**
	 *  method is used for checking valid email id format.
	 *  @param email
	 *  @return boolean true for valid false for invalid
	 */
	public static boolean isEmailValid(String email) {
	    boolean isValid = false;

	    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
	    CharSequence inputStr = email;

	    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(inputStr);
	    if (matcher.matches()) {
	        isValid = true;
	    }
	    return isValid;
	}
	private class RegisterUser extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(RegisterActivity.this);
			// pDialog.setIcon(R.drawable.help);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang đăng kí...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String name = params[0];
			String email = params[1];
			String password = params[2];
			
			JSONObject json = userFunction.registerUser(name, email, password);
			try {
				if(json.getString(KEY_SUCCESS) != null){
					String res = json.getString(KEY_SUCCESS);
					if(Integer.parseInt(res) == 1){
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								animatedStartActivity();
							}
						});

					} else {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								alertDialogManager.showAlertDialog(RegisterActivity.this, "Đăng kí", 
										"Đã xảy ra lỗi trong quá trình đăng kí, vui lòng thử lại!", false);
							}
						});
					}
				}
			} catch (JSONException e) {
                e.printStackTrace();
            }

			return null;
		}
		
	}
	private void showAlertDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(RegisterActivity.this);
 
        // Setting Dialog Title
        dialog.setTitle("Kết nối Internet");
 
        // Setting Dialog Message
        dialog.setMessage("Thiết bị chưa kết nối internet, vui lòng bật kết nối internet!");
 
        dialog.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
			}
		});
        dialog.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
        // Setting alert dialog icon
        dialog.setIcon(R.drawable.intetnet);
 
        AlertDialog alert = dialog.create();
        alert.show();
    }
}

